package cn.plushine.utils;


import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 七牛云文件上传
 */
@Getter
@Component
@ConfigurationProperties(prefix = "qiniu")
public class UploadUtils {
    // 图床域名
    private static String url;
    // ak
    private static String accessKey;
    // sk
    private static String secretKey;
    // 空间名称
    private static String bucket;


    // 使用文件流上传文件到七牛云
    public static String uploadFile(MultipartFile multipartFile) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        // 存储上传结果
        DefaultPutRet putRet = null;

        // 获取文件流
        byte[] uploadBytes = multipartFile.getBytes();

        // 权限验证，获取token
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        // 上传文件
        Response response = uploadManager.put(uploadBytes, key, upToken);
        //解析上传成功的结果
        putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        // 上传成功，响应图片链接
        return url + "/" + putRet.hash;
    }

    public static String getUrl() {
        return url;
    }

    /**
     * 由于ConfigurationProperties只能调用非静态的set方法
     * 故，如果不将方法设置为非静态，自动配置的属性值均为null
     */
    public void setUrl(String url) {
        UploadUtils.url = url;
    }

    public void setAccessKey(String accessKey) {
        UploadUtils.accessKey = accessKey;
    }

    public void setSecretKey(String secretKey) {
        UploadUtils.secretKey = secretKey;
    }

    public void setBucket(String bucket) {
        UploadUtils.bucket = bucket;
    }
}
